<!DOCTYPE html>
<html>
<head>
    {% include 'system/common/header.html' %}
    <style>
        .pear-container {
            background-color: white;
        }

        body {
            margin: 10px;
        }

        .layui-form-item {
            margin-bottom: 20px;
        }

        .upload-options {
            border: 1px solid #e6e6e6;
            padding: 15px;
            margin: 15px 0;
            border-radius: 5px;
            background-color: #fafafa;
        }

        .option-title {
            font-weight: bold;
            color: #333;
            margin-bottom: 10px;
        }

        .upload-progress {
            display: none;
            margin-top: 15px;
        }

        .preview-area {
            border: 2px dashed #ccc;
            border-radius: 8px;
            padding: 20px;
            text-align: center;
            margin: 15px 0;
            min-height: 100px;
            transition: border-color 0.3s ease;
        }

        .preview-area:hover {
            border-color: #999;
        }

        .preview-image {
            max-width: 100%;
            max-height: 200px;
            margin: 10px 0;
            border-radius: 5px;
            box-shadow: 0 2px 8px rgba(0,0,0,0.1);
        }

        .file-info {
            background: #f8f9fa;
            border: 1px solid #e9ecef;
            border-radius: 4px;
            padding: 10px;
            margin: 10px 0;
            font-size: 12px;
            color: #666;
        }
    </style>
</head>
<body>
<div class="layui-row layui-col-space15">
    <div class="layui-col-md12">
        <div class="layui-card">
            <div class="layui-card-header">
                <h3>高级图片上传</h3>
                <p style="color: #666; font-size: 14px;">支持多种上传选项和图片处理功能</p>
            </div>
            <div class="layui-card-body">
                <form class="layui-form edit-form">
                    <!-- 文件选择区域 -->
                    <div class="layui-form-item">
                        <label class="layui-form-label">选择图片</label>
                        <div class="layui-input-block">
                            <div class="preview-area" id="preview-area">
                                <i class="layui-icon layui-icon-upload" style="font-size: 30px; color: #ccc;"></i>
                                <p>点击选择图片或将图片拖拽到此区域</p>
                                <p style="color: #999; font-size: 12px;">支持 JPG、PNG、GIF、WebP 格式</p>
                            </div>
                            <button type="button" class="layui-btn layui-btn-normal" id="select-file">
                                <i class="layui-icon layui-icon-upload"></i> 选择文件
                            </button>
                        </div>
                    </div>

                    <!-- 基础设置 -->
                    <div class="upload-options">
                        <div class="option-title">基础设置</div>
                        
                        <div class="layui-form-item">
                            <label class="layui-form-label">上传方式</label>
                            <div class="layui-input-block">
                                <input type="radio" name="upload_type" value="local" title="本地存储" checked>
                                <input type="radio" name="upload_type" value="qiniu" title="七牛云存储">
                            </div>
                        </div>

                        <div class="layui-form-item">
                            <label class="layui-form-label">文件大小限制</label>
                            <div class="layui-input-inline" style="width: 100px;">
                                <input type="number" name="max_size" value="10" min="1" max="100" class="layui-input">
                            </div>
                            <div class="layui-form-mid">MB</div>
                        </div>
                    </div>

                    <!-- 图片处理选项 -->
                    <div class="upload-options">
                        <div class="option-title">图片处理选项</div>
                        
                        <div class="layui-form-item">
                            <div class="layui-input-block">
                                <input type="checkbox" name="create_thumbnail" lay-skin="primary" title="创建缩略图" checked>
                                <input type="checkbox" name="compress_image" lay-skin="primary" title="压缩图片" checked>
                            </div>
                        </div>

                        <div class="layui-form-item">
                            <label class="layui-form-label">压缩质量</label>
                            <div class="layui-input-block">
                                <div id="quality-slider"></div>
                                <div style="text-align: center; margin-top: 5px;">
                                    <span id="quality-value">85</span>%
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- 文件信息显示 -->
                    <div class="file-info" id="file-info" style="display: none;">
                        <div class="option-title">文件信息</div>
                        <div id="file-details"></div>
                    </div>

                    <!-- 上传按钮 -->
                    <div class="layui-form-item">
                        <div class="layui-input-block">
                            <button type="button" class="layui-btn layui-btn-lg" id="upload-button" disabled>
                                <i class="layui-icon layui-icon-upload"></i> 开始上传
                            </button>
                            <button type="button" class="layui-btn layui-btn-primary layui-btn-lg" onclick="history.back()">
                                <i class="layui-icon layui-icon-return"></i> 返回
                            </button>
                        </div>
                    </div>

                    <!-- 上传进度 -->
                    <div class="upload-progress" id="upload-progress">
                        <div class="layui-progress" lay-filter="upload-progress-bar" lay-showpercent="true">
                            <div class="layui-progress-bar" lay-percent="0%">
                                <span class="layui-progress-text">0%</span>
                            </div>
                        </div>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>

{% include 'system/common/footer.html' %}

<script>
    layui.use(['jquery', 'element', 'form', 'upload', 'slider'], function () {
        var $ = layui.jquery;
        var element = layui.element;
        var form = layui.form;
        var upload = layui.upload;
        var slider = layui.slider;

        var selectedFile = null;
        var uploadQuality = 85;

        // 初始化质量滑块
        slider.render({
            elem: '#quality-slider',
            value: uploadQuality,
            min: 10,
            max: 100,
            step: 5,
            change: function(value) {
                uploadQuality = value;
                $('#quality-value').text(value);
            }
        });

        // 文件选择器
        var uploadInst = upload.render({
            elem: '#select-file',
            auto: false,
            accept: 'images',
            acceptMime: 'image/*',
            exts: 'jpg|jpeg|png|gif|webp|bmp',
            size: 50 * 1024, // 50MB
            choose: function(obj) {
                obj.preview(function(index, file, result) {
                    selectedFile = file;
                    showFilePreview(file, result);
                    $('#upload-button').prop('disabled', false);
                });
            }
        });

        // 显示文件预览
        function showFilePreview(file, result) {
            var previewHtml = '<img src="' + result + '" class="preview-image" alt="预览图片">';
            $('#preview-area').html(previewHtml);

            // 显示文件信息
            var fileSize = (file.size / 1024 / 1024).toFixed(2);
            var fileInfo = '<strong>文件名:</strong> ' + file.name + '<br>' +
                          '<strong>文件大小:</strong> ' + fileSize + ' MB<br>' +
                          '<strong>文件类型:</strong> ' + file.type + '<br>' +
                          '<strong>最后修改:</strong> ' + new Date(file.lastModified).toLocaleString();
            
            $('#file-details').html(fileInfo);
            $('#file-info').show();
        }

        // 上传按钮点击事件
        $('#upload-button').click(function() {
            if (!selectedFile) {
                layer.msg('请先选择文件', {icon: 2});
                return;
            }

            var formData = new FormData();
            formData.append('file', selectedFile);
            formData.append('upload_type', $('input[name="upload_type"]:checked').val());
            formData.append('max_size', $('input[name="max_size"]').val());
            formData.append('create_thumbnail', $('input[name="create_thumbnail"]').prop('checked'));
            formData.append('compress_image', $('input[name="compress_image"]').prop('checked'));

            // 显示上传进度
            $('#upload-progress').show();
            $('#upload-button').prop('disabled', true).html('<i class="layui-icon layui-icon-loading layui-anim layui-anim-rotate layui-anim-loop"></i> 上传中...');
            
            // 初始化进度条
            updateProgress(0);

            // 执行上传
            $.ajax({
                url: "/system/file/upload-advanced",
                type: 'POST',
                data: formData,
                processData: false,
                contentType: false,
                xhr: function() {
                    var xhr = $.ajaxSettings.xhr();
                    if (xhr.upload) {
                        xhr.upload.addEventListener('progress', function(e) {
                            if (e.lengthComputable) {
                                var percentComplete = (e.loaded / e.total) * 100;
                                updateProgress(Math.round(percentComplete));
                            }
                        }, false);
                    }
                    return xhr;
                },
                success: function(res) {
                    updateProgress(100);
                    if (res.success) {
                        layer.msg(res.msg, {icon: 1, time: 1500}, function() {
                            // 显示上传结果
                            showUploadResult(res.data);
                            // 重置表单
                            resetForm();
                            // 通知父页面刷新表格
                            if (parent && parent.window.refresh) {
                                parent.window.refresh();
                            }
                        });
                    } else {
                        layer.msg(res.msg, {icon: 2});
                        $('#upload-button').prop('disabled', false).html('<i class="layui-icon layui-icon-upload"></i> 重新上传');
                    }
                },
                error: function(xhr, status, error) {
                    layer.msg('上传失败: ' + error, {icon: 2});
                    $('#upload-button').prop('disabled', false).html('<i class="layui-icon layui-icon-upload"></i> 重新上传');
                },
                complete: function() {
                    setTimeout(function() {
                        $('#upload-progress').hide();
                    }, 1000);
                }
            });
        });
        
        // 更新进度条的函数
        function updateProgress(percent) {
            try {
                // 使用Layui的element模块更新进度条
                element.progress('upload-progress-bar', percent + '%');
            } catch (e) {
                // 如果Layui方法失败，使用jQuery直接操作
                var progressBar = $('#upload-progress .layui-progress-bar');
                var progressText = $('#upload-progress .layui-progress-text');
                
                progressBar.css('width', percent + '%').attr('lay-percent', percent + '%');
                progressText.text(percent + '%');
                
                // 如果没有进度文本元素，则创建一个
                if (progressText.length === 0) {
                    progressBar.html('<span class="layui-progress-text">' + percent + '%</span>');
                }
            }
        }

        // 显示上传结果
        function showUploadResult(data) {
            var resultHtml = '<div style="text-align: center; padding: 20px;">' +
                            '<h3 style="color: #5FB878;">上传成功！</h3>' +
                            '<p>文件URL: <a href="' + data.src + '" target="_blank">' + data.src + '</a></p>';
            
            if (data.file_info && data.file_info.thumbnail_url) {
                resultHtml += '<p>缩略图: <a href="' + data.file_info.thumbnail_url + '" target="_blank">查看缩略图</a></p>';
            }
            
            resultHtml += '<div style="margin: 15px 0;">' +
                         '<button type="button" class="layui-btn" onclick="location.reload()">继续上传</button> ' +
                         '<button type="button" class="layui-btn layui-btn-primary" onclick="closeAndRefresh()">关闭</button>' +
                         '</div></div>';

            $('#preview-area').html(resultHtml);
        }

        // 关闭并刷新父页面表格
        function closeAndRefresh() {
            // 通知父页面刷新表格
            if (parent && parent.window.refresh) {
                parent.window.refresh();
            }
            // 关闭当前弹窗
            parent.layer.close(parent.layer.getFrameIndex(window.name));
        }

        // 重置表单
        function resetForm() {
            selectedFile = null;
            $('#file-info').hide();
            $('#upload-button').prop('disabled', true).html('<i class="layui-icon layui-icon-upload"></i> 开始上传');
        }

        // 拖拽上传支持
        var previewArea = document.getElementById('preview-area');
        
        ['dragenter', 'dragover', 'dragleave', 'drop'].forEach(eventName => {
            previewArea.addEventListener(eventName, preventDefaults, false);
        });

        function preventDefaults(e) {
            e.preventDefault();
            e.stopPropagation();
        }

        ['dragenter', 'dragover'].forEach(eventName => {
            previewArea.addEventListener(eventName, highlight, false);
        });

        ['dragleave', 'drop'].forEach(eventName => {
            previewArea.addEventListener(eventName, unhighlight, false);
        });

        function highlight(e) {
            previewArea.style.borderColor = '#5FB878';
            previewArea.style.backgroundColor = '#f8fff8';
        }

        function unhighlight(e) {
            previewArea.style.borderColor = '#ccc';
            previewArea.style.backgroundColor = '';
        }

        previewArea.addEventListener('drop', handleDrop, false);

        function handleDrop(e) {
            var dt = e.dataTransfer;
            var files = dt.files;
            
            if (files.length > 0) {
                var file = files[0];
                if (file.type.startsWith('image/')) {
                    selectedFile = file;
                    var reader = new FileReader();
                    reader.onload = function(e) {
                        showFilePreview(file, e.target.result);
                        $('#upload-button').prop('disabled', false);
                    };
                    reader.readAsDataURL(file);
                } else {
                    layer.msg('请选择图片文件', {icon: 2});
                }
            }
        }
    });
</script>
</body>
</html>